/**
 * @author [siwi]
 * @email [siwi@siwi.me]
 * @create date 2017-05-30 04:52:18
 * @modify date 2017-05-30 04:52:18
 * @desc [description]
*/
const mongoose = require('mongoose')
const crypto = require('crypto')
const Schame = mongoose.Schema
const { plugin } = require('../config/database')
const Conf = require('../config/config')

const User = new Schame({
  username: {
    type: String,
    required: true,
  },
  password: {
    type: String,
    required: true,
  },
  displayName: {
    type: String,
    default: 'User',
  },
})
User.plugin(plugin)

/**
 * 虚拟字段
 */
User.virtual('avatar').get(() => {
  return Conf.defaultAvatar
})
/**
 * password写入时加密
 */
User.path('password').set((password) => {
  return crypto.createHash('md5').update(password).digest('base64')
})

/**
 * 验证用户名密码是否正确
 */
User.statics.check_password = async (username, password) => {
  let user = await User.findOne({
    username: username,
    password: crypto.createHash('md5').update(password).digest('base64')
  })
  return user
}

module.exports = mongoose.model('User', User)